$(function () {

});

function login(publicKey) {

     let u = $("#form-username").val();
     let p = $("#form-password").val();


     console.log(u);
     console.log(p);
    const encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    const userId = encrypt.encrypt(u);
    const passWord = encrypt.encrypt(md5(p));

    $.ajax({
        url: "/login",
        type: "post",
        data: {
            "u": userId,
            "p": passWord
        },
        success: function (response) {
            if (response.code == 200) {
                let data = response.data;
                if (data.role == 1){
                    localStorage.setItem("userInfo", JSON.stringify(data.msg));
                    location.href = "/index.html";
                }else{
                    localStorage.setItem("admin",JSON.stringify(data.msg));
                    location.href = "/admin.html";
                }

            } else {
                layer.msg(response.message);
            }
        },

        error: function () {

        },
        beforeSend: function () {
            showProgress();
        },
        complete:function () {
            layer.closeAll('loading');
        }
    })
}


function getPublicKey() {

    let u = $("#form-username").val();
    let p = $("#form-password").val();

    if ($.trim(u) .length == 0){
        layer.tips('Pleace Enter Your Account！', '#form-username', {
            tips: [1, '#ff0000'],
            time: 4000
        });
        return;
    }
    if ($.trim(p) .length == 0){
        layer.tips('Pleace Enter Your Password！', '#form-password', {
            tips: [1, '#ff0000'],
            time: 4000
        });
        return;
    }
    $.ajax({
        url: "/public",
        type: "get",
        success: function (response) {
            if (response.code == 200) {
                login(response.data);
            } else {
                layer.msg(response.message);
            }
        },
        error: function () {
            layer.msg("您的网络可能出现了一点问题");
        },
        beforeSend: function () {
            showProgress();
        },
        complete: function () {
            layer.closeAll('loading');
        }
    })
}

function showProgress() {
    layer.load(0, {
        shade: [0.5, '#fff'] //0.1透明度的白色背景
    });
}